﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;

namespace ZBJF.Warranty.BLL
{
    public partial class InsuranceProductOrderCardService
    {
        public InsuranceProductOrderCard LoadById(int id)
        {
            return LoadEntities(o => o.ID == id).FirstOrDefault();
        }

        public IQueryable<InsuranceProductOrderCard> Load(string cardNo, string password)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();

            expressionWhere = expressionWhere.And(o => o.CardNo.Equals(cardNo, StringComparison.CurrentCultureIgnoreCase) &&
                o.CardPassword.Equals(password));
            return LoadEntities(expressionWhere);
        }

        public IQueryable<InsuranceProductOrderCard> LoadByInsuranceProductOrderId(int insuranceProductOrderId)
        {
            return LoadEntities(o => o.InsuranceProductOrderId == insuranceProductOrderId);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cardCount">保险卡产品的数量</param>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateCard(int cardCount, InsuranceProductOrderCard model)
        {
            var validateCode = new ValidateCode();
            var insuranceProductList = ServiceFactory.InsuranceProductsServiceInstance.LoadAllInsuranceProductsBy(model.SellerInsuranceProductId).AsNoTracking().ToList();
            for (int i = 0; i < cardCount; i++)
            {
                //同一个保险卡产品用同一个卡号密码
                var cardNo = DateTime.Now.ToString("yyMMddHHmmfff");
                var cardPassword = validateCode.CreateValidateCode(6);
                //一定要配置了基础产品
                if (insuranceProductList.Any())
                {
                    for (int j = 0; j < insuranceProductList.Count; j++)
                    {
                        var insuranceProduct = insuranceProductList[j];
                        //if (!insuranceProduct.IsCardProduct)//非卡产品不生成卡密
                        //    continue;
                        var insuranceProductPackage = insuranceProduct.InsuranceProductPackageMapping.FirstOrDefault(o => o.InsuranceProductId == insuranceProduct.ID);//打包产品
                        var card = new InsuranceProductOrderCard
                        {
                            ActiveCardInLimitDays = insuranceProductPackage != null ? insuranceProductPackage.InsuranceProductPackage.ActiveCardInLimitDays : int.MaxValue,
                            CardNo = cardNo,
                            CardPassword = cardPassword,
                            CreateTime = DateTime.Now,
                            InsuranceProductName = insuranceProduct.ProductName,
                            InsuranceProductOrderId = model.InsuranceProductOrderId,
                            SellerInsuranceProductId = model.SellerInsuranceProductId,
                            InsuranceProductId = insuranceProduct.ID,
                            SellerEmployeeID = model.SellerEmployeeID,
                            SellerEmployeeName = model.SellerEmployeeName,
                            BuyUserName = model.BuyUserName,
                            BuyUserIDNo = model.BuyUserIDNo,
                            Status = (byte)InsuranceProductOrderCardStatus.UnActivate
                        };
                        ServiceFactory.InsuranceProductOrderCardServiceInstance.AddEntities(card);
                    }
                }
            }
            return true;
        }
        public IQueryable<InsuranceProductOrderCard> GetPagingList(InsuranceProductOrderCardModel model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();
            if (model.SellerInsuranceProductId.HasValue)
            {
                expressionWhere =
                   expressionWhere.And(o => o.SellerInsuranceProductId == model.SellerInsuranceProductId.Value);
            }
            if (model.InsuranceProductId.HasValue)
            {
                expressionWhere =
                   expressionWhere.And(o => o.InsuranceProductId == model.InsuranceProductId.Value);
            }
            if (model.InsuranceProductOrderId.HasValue)
            {
                expressionWhere =
                    expressionWhere.And(o => o.InsuranceProductOrderId == model.InsuranceProductOrderId.Value);
            }
            if (model.Status.HasValue)
            {
                expressionWhere =
                    expressionWhere.And(o => o.Status == model.Status.Value);
            }
            if (model.MonthDateTime.HasValue)
            {
                var dtMonth = model.MonthDateTime.Value.ToString("yyyyMM");
                expressionWhere = expressionWhere.And(o => SqlFunctions.DateName("yyyy", o.CreateTime) + SqlFunctions.DateName("MM", o.CreateTime) == dtMonth);
            }
            if (model.SellerEmployeeID.HasValue)
            {
                expressionWhere =
                    expressionWhere.And(o => o.SellerEmployeeID == model.SellerEmployeeID.Value);
            }

            return LoadPagerEntities<InsuranceProductOrderCard>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }

        /// <summary>
        /// 验证卡号密码
        /// </summary>
        /// <param name="insuranceProductId"></param>
        /// <param name="cardNo">卡号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool ValidateCardPassword(long insuranceProductId, string cardNo, string password)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();

            expressionWhere = expressionWhere.And(o => o.InsuranceProductId == insuranceProductId && o.CardNo.Equals(cardNo, StringComparison.CurrentCultureIgnoreCase) &&
                o.CardPassword.Equals(password) &&
                o.Status == (byte)InsuranceProductOrderCardStatus.UnActivate &&
                SqlFunctions.DateAdd("dd", o.ActiveCardInLimitDays, o.CreateTime) <= DateTime.Now);
            return LoadEntities(expressionWhere).Any();
        }

        /// <summary>
        /// 使用卡号密码，更新状态
        /// </summary>
        /// <param name="insuranceProductId"></param>
        /// <param name="cardNo"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool UseCard(long insuranceProductId, string cardNo, string password)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();
            expressionWhere = expressionWhere.And(o => o.InsuranceProductId == insuranceProductId && o.CardNo.Equals(cardNo, StringComparison.CurrentCultureIgnoreCase) && o.CardPassword.Equals(password) && o.Status == (byte)InsuranceProductOrderCardStatus.UnActivate && SqlFunctions.DateAdd("dd", o.ActiveCardInLimitDays, o.CreateTime) <= DateTime.Now);
            var insuranceProductOrderCard = LoadEntities(expressionWhere).FirstOrDefault();
            if (insuranceProductOrderCard != null)
            {
                insuranceProductOrderCard.Status = (byte)InsuranceProductOrderCardStatus.Activated;
                insuranceProductOrderCard.ActiveTime = DateTime.Now;
                return UpdateEntities(insuranceProductOrderCard);
            }
            return false;
        }

        /// <summary>
        /// 获取产品某一状态的数量（已销售（待激活），已激活，已过期）
        /// </summary>
        /// <param name="sellerInsuranceProductId">商户产品ID</param>
        /// <param name="insuranceProductId">产品ID</param>
        /// <param name="status">状态,不传即获取销量</param>
        /// <param name="employeeId">销售员，不传不过滤销售员</param>
        /// <returns></returns>
        public int GetInsuranceCardCount(long sellerInsuranceProductId, long insuranceProductId, long employeeId = 0, InsuranceProductOrderCardStatus status = 0)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();
            if (sellerInsuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductId == sellerInsuranceProductId);
            }
            if (insuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.InsuranceProductId == insuranceProductId);
            }
            if (employeeId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == employeeId);
            }
            if (status > 0)
            {
                expressionWhere = expressionWhere.And(o => o.Status == (byte)status);
            }
            return LoadEntities(expressionWhere).Count();
        }

        public int GetSellerInsuranceCardCount(long sellerInsuranceProductId, InsuranceProductOrderCardStatus status = 0)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();
            if (sellerInsuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductId == sellerInsuranceProductId);
            }
            if (status > 0)
            {
                expressionWhere = expressionWhere.And(o => o.Status == (byte)status);
            }
            return LoadEntities(expressionWhere).Count();
        }

        public int GetInsuranceCardSaleCount(string dtMonth, long employeeId, long sellerInsuranceProductId = 0, long insuranceProductId = 0, InsuranceProductOrderCardStatus status = 0)
        {
            var expressionWhere = PredicateExtensions.True<InsuranceProductOrderCard>();
            if (!string.IsNullOrEmpty(dtMonth))
            {
                expressionWhere = expressionWhere.And(o => SqlFunctions.DateName("yyyy", o.CreateTime) + SqlFunctions.DateName("MM", o.CreateTime) == dtMonth);
            }
            if (employeeId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerEmployeeID == employeeId);
            }
            if (sellerInsuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.SellerInsuranceProductId == sellerInsuranceProductId);
            }
            if (insuranceProductId > 0)
            {
                expressionWhere = expressionWhere.And(o => o.InsuranceProductId == insuranceProductId);
            }
            if ((byte)status > 0)
            {
                expressionWhere = expressionWhere.And(o => o.Status == (byte)status);
            }
            return LoadEntities(expressionWhere).Count();
        }


    }
}
